package com.manzuo.framework.datasource;

/**
 * 绑定到当前线程的读写状态上下文环境。
 * 用于读写分离。
 * @author 高恒
 */
public class ReadWriteContext {
	
	private static ReadWriteThreadLocal flag =  new ReadWriteThreadLocal();
	private static ReadWriteThreadLocal pre =  new ReadWriteThreadLocal();

	public static void toggleWrite() {
		pre.set(getFlag());
		flag.set(ReadWriteFlag.write);
	}
	
	public static void toggleRead() {
		pre.set(getFlag());
		flag.set(ReadWriteFlag.read);
	}
	
	public static void reset() {
		pre.set(null);
		flag.set(getPreFlag());
	}
	
	public static ReadWriteFlag getFlag() {
		return flag.get() == null ? ReadWriteFlag.read : flag.get();
	}
	
	public static ReadWriteFlag getPreFlag() {
		return pre.get() == null ? ReadWriteFlag.read : pre.get();
	}
}
